//
//  WeatherViewController.m
//  pocketNews
//
//  Created by DS on 2018/10/31.
//  Copyright © 2018年 徐双. All rights reserved.
//

#import "WeatherViewController.h"
#import "WeatherTableViewCell.h"

#import "SDCityPickerViewController.h"
#import "SDCityInitial.h"
#import "SDCityModel.h"

#import "WeatherModel.h"



#define historyCityFilepath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"historyCity.data"]

@interface WeatherViewController ()<UITableViewDelegate,UITableViewDataSource>

Strong UITableView * tableView;

Strong UIView * headerView;



Strong UILabel * numLabel;

Strong UILabel * stausLabel;

Strong UILabel * timeLabel;





@property (nonatomic,strong)NSMutableArray *dataArr;

/**
 热门
 */
@property (nonatomic,strong)NSMutableArray *hotArr;


/**
 历史
 */
@property (nonatomic,strong)NSMutableArray *historyArr;


/**
 当前选择
 */
@property (nonatomic,strong)NSMutableArray *selectArr;

@property (nonatomic,strong)UIButton *btn; //左按钮
@property (nonatomic,strong)NSMutableArray *historySelectArr;
@property (nonatomic,strong)UILabel *label;

Strong  UIButton * palceBtn;

Strong NSDictionary * dictShow;

Strong NSMutableArray * lifeArr;


//实况天气

Strong NSMutableArray * nowWeatherArr;


//日出日落

Strong NSMutableArray * sunArr;

Strong NSDictionary * sunDic;




@end

//网络
@implementation WeatherViewController (NetWorking)

//实况天气
- (void)getWetherData{
    
//    if (!self.cityName) {
//        self.cityName = @"沈阳";
//    }

    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 
                                 @"location":self.cityName,
                                 @"lang":@"cn",
                                 @"unit":@"m",
                                 @"key":@"9623bb60bd13471bae00e5ea937b470c"
                                 }.mutableCopy;
    
    [[AFAppDotNetAPIClient sharedClient] POST:@"https://free-api.heweather.com/s6/weather/now?" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
    
        for (NSDictionary * dic1 in responseObject[@"HeWeather6"]) {
         
                if ([dic1[@"status"] isEqualToString:@"ok"]) {

                    NSDictionary * dic = dic1[@"now"];
                    
                    self.dictShow = dic1[@"now"];
                        
                    self.numLabel.text = [NSString stringWithFormat:@"%@",dic[@"tmp"]];
                    
                    self.stausLabel.text = [NSString stringWithFormat:@"%@",dic[@"cond_txt"]];
                    
                  
                    
                    NSDictionary * dic2 = dic1[@"update"];
                    
                    self.timeLabel.text = dic2[@"loc"];
                }
        }
        
        [self.view addSubview:self.tableView];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


//💰三天
- (void)getheWewaatherData{
    
//    if (!self.cityName) {
//        self.cityName = @"沈阳";
//    }
    
    self.nowWeatherArr = [NSMutableArray array];
 
    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 
                                 @"location":self.cityName,
                                 @"lang":@"cn",
                                 @"unit":@"m",
                                 @"key":@"9623bb60bd13471bae00e5ea937b470c"
                                 }.mutableCopy;
    
    [[AFAppDotNetAPIClient sharedClient] POST:@"https://free-api.heweather.com/s6/weather/forecast?" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
      
        for (NSDictionary * dic1 in responseObject[@"HeWeather6"]) {
            
            if ([dic1[@"status"] isEqualToString:@"ok"]) {
                
                for (NSDictionary * dic  in dic1[@"daily_forecast"]) {
                    
                    WeatherNowModel * model = [[WeatherNowModel alloc] init];
                    
                    [model WeatherNowModelWithDic:dic];
                    
                    [self.nowWeatherArr addObject:model];
                }
            }
        }
    
       [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}



//生活指数
- (void)getLifeData{
    
//    if (!self.cityName) {
//        self.cityName = @"沈阳";
//    }
    
    self.lifeArr = [NSMutableArray array];
    
    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 
                                 @"location":self.cityName,
                                 @"lang":@"cn",
                                 @"unit":@"m",
                                 @"key":@"9623bb60bd13471bae00e5ea937b470c"
                                 }.mutableCopy;
    
    [[AFAppDotNetAPIClient sharedClient] POST:@"https://free-api.heweather.com/s6/weather/lifestyle?" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        
     
        
        for (NSDictionary * dic1 in responseObject[@"HeWeather6"]) {
            
            if ([dic1[@"status"] isEqualToString:@"ok"]) {
                
                self.lifeArr = dic1[@"lifestyle"];
                
            }
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


//生活指数
- (void)getSunData{
    
//    if (!self.cityName) {
//        self.cityName = @"沈阳";
//    }
    
    self.sunArr = [NSMutableArray array];
    self.sunDic = [NSMutableDictionary dictionary];
    
    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 
                                 @"location":self.cityName,
                                 @"lang":@"cn",
                                 @"unit":@"m",
                                 @"key":@"9623bb60bd13471bae00e5ea937b470c"
                                 }.mutableCopy;
    
    [[AFAppDotNetAPIClient sharedClient] POST:@"https://free-api.heweather.com/s6/solar/sunrise-sunset?" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        
        
        
        for (NSDictionary * dic1 in responseObject[@"HeWeather6"]) {
            
            if ([dic1[@"status"] isEqualToString:@"ok"]) {
                
                self.sunArr = dic1[@"sunrise_sunset"];
                
                self.sunDic = dic1[@"update"];
                
            }
        }
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}





@end

@implementation WeatherViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
     [self getWetherData];
    
     [self getheWewaatherData];
    
     [self getLifeData];
    
    [self getSunData];
    
}




- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"天气";
    
     [self.view addSubview:self.tableView];
    
    UIButton *btn1 =[[UIButton alloc]initWithFrame:CGRectMake(0,0, 22, 22)];
    
    [btn1 addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
    [btn1 setBackgroundImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:btn1];
    self.navigationItem.leftBarButtonItem  = item;
    
   
}

-(void)onClick:(UIButton *)btn{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)placeBtnClick{
    
    SDCityPickerViewController *city =[[SDCityPickerViewController alloc]init];
    city.cityPickerBlock = ^(SDCityModel *city)
    {
        self.navigationItem.title = city.name;
        [self.historyArr insertObject:city atIndex:0];
        [self setSelectCityModel:city];
        
        self.cityName = city.name;
        
        [self.palceBtn setTitle:city.name forState:UIControlStateNormal];
        
        [self getWetherData];
        [self getheWewaatherData];
        [self getLifeData];
        //self.label.text = [NSString stringWithFormat:@"当前选择城市:%@",city.name];
    };
    city.dataArr = [NSMutableArray arrayWithArray:self.dataArr];
    [self.navigationController pushViewController:city animated:YES];
    
    
}

-(void)setSelectCityModel:(SDCityModel *)city{
    
    [self.historyArr removeAllObjects];
    
    SDCityInitial *cityInitial = [[SDCityInitial alloc]init];
    cityInitial.initial = @"历史";
    
    [self historySelectArr];
    //    [_historySelectArr removeObject:city];
    //    [_historySelectArr insertObject:city atIndex:0];
    
    NSMutableArray *emptyArr =[NSMutableArray arrayWithArray:_historySelectArr];
    
    //    for (SDCityModel *hiscity in emptyArr) {
    //        if ([hiscity.name isEqualToString:city.name]) {
    //            [_historySelectArr removeObject:city];
    //        }
    //    }
    
    [emptyArr enumerateObjectsUsingBlock:^(SDCityModel  *_Nonnull hiscity, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([hiscity.name isEqualToString:city.name]) {
            [self->_historySelectArr removeObjectAtIndex:idx];
            *stop =YES;
        }
        
    }];
    
    
    [_historySelectArr insertObject:city atIndex:0];
    
    if (_historySelectArr.count>6){
        [_historySelectArr removeLastObject];
    }
    
    [NSKeyedArchiver archiveRootObject:_historySelectArr toFile:historyCityFilepath];
    
    cityInitial.cityArrs = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:historyCityFilepath]];
    
    
    
    [self.historyArr addObject:cityInitial];
    
    [self.dataArr replaceObjectsAtIndexes:[NSIndexSet indexSetWithIndex:1] withObjects:self.historyArr];
}


/**
 定位选择
 
 */
-(NSMutableArray *)selectArr{
    if (!_selectArr){
        _selectArr = [NSMutableArray array];
        SDCityInitial *cityInitial =[[SDCityInitial alloc]init];
        cityInitial.initial = @"定位";
        SDCityModel *city = [[SDCityModel alloc]init];
        city.name = self.cityName;
        NSMutableArray *selectArrs =[NSMutableArray array];
        [selectArrs addObject:city];
        cityInitial.cityArrs = selectArrs;
        [_selectArr addObject:cityInitial];
        
    }
    return _selectArr;
}

/**
 历史
 
 */
-(NSMutableArray *)historyArr{
    if (!_historyArr){
        _historyArr = [NSMutableArray array];
        SDCityInitial *cityInitial =[[SDCityInitial alloc]init];
        cityInitial.initial = @"历史";
        cityInitial.cityArrs = self.historySelectArr;
        
        
        [_historyArr addObject:cityInitial];
    }
    return _historyArr;
}
-(NSMutableArray *)historySelectArr{
    if (!_historySelectArr){
        _historySelectArr = [NSKeyedUnarchiver unarchiveObjectWithFile:historyCityFilepath];
        if (!_historySelectArr){
            _historySelectArr =[NSMutableArray array];
        }
    }
    return _historySelectArr;
}

/**
 热门
 
 */
-(NSMutableArray *)hotArr{
    if(!_hotArr){
        _hotArr = [NSMutableArray array];
        SDCityInitial *cityInitial =[[SDCityInitial alloc]init];
        cityInitial.initial = @"热门";
        
        NSArray *hotCityArr =@[@{@"id":@"1",@"name":@"北京",@"pid":@"11"},
                               @{@"id":@"2",@"name":@"上海",@"pid":@"11"},
                               @{@"id":@"3",@"name":@"广州",@"pid":@"11"},
                               @{@"id":@"4",@"name":@"深圳",@"pid":@"11"},
                               @{@"id":@"4",@"name":@"成都",@"pid":@"11"},
                               @{@"id":@"4",@"name":@"杭州",@"pid":@"11"},
                               ];
        NSMutableArray *hotarrs =[NSMutableArray array];
        
        for (NSDictionary *dic in hotCityArr){
            SDCityModel *city = [SDCityModel cityWithDict:dic];
            [hotarrs addObject:city];
        }
        cityInitial.cityArrs = hotarrs;
        [_hotArr addObject:cityInitial];
    }
    return _hotArr;
    
}


-(NSMutableArray *)dataArr{
    if (!_dataArr){
        
        _dataArr =[NSMutableArray array];
        
        
        
        NSString *path =[[NSBundle mainBundle]pathForResource:@"City" ofType:@"plist"];
        
        
        NSArray *arr =[NSArray arrayWithContentsOfFile:path];
        
        NSMutableArray *cityModels = [NSMutableArray array];
        
        //获取全部城市cityModel
        for (NSDictionary *dic in arr){
            for (NSDictionary *dict in dic[@"children"]){
                SDCityModel *cityModel = [SDCityModel cityWithDict:dict];
                [cityModels addObject:cityModel];
            }
        }
        
        //获取首字母
        NSMutableArray *indexArr =
        [[cityModels valueForKeyPath:@"firstLetter"] valueForKeyPath:@"@distinctUnionOfObjects.self"];
        
        //遍历数组
        for (NSString *indexStr in indexArr) {
            
            SDCityInitial *cityInitial =[[SDCityInitial alloc]init];
            cityInitial.initial = indexStr;
            NSMutableArray *cityArrs =[NSMutableArray array];
            for ( SDCityModel *cityModel in cityModels) {
                if ([indexStr isEqualToString:cityModel.firstLetter]) {
                    [cityArrs addObject:cityModel];
                    
                }
            }
            cityInitial.cityArrs = cityArrs;
            [_dataArr addObject:cityInitial];
        }
        
        
        [_dataArr insertObjects:self.hotArr atIndexes:[NSIndexSet indexSetWithIndex:0]];
        [_dataArr insertObjects:self.historyArr atIndexes:[NSIndexSet indexSetWithIndex:0]];
        [_dataArr insertObjects:self.selectArr atIndexes:[NSIndexSet indexSetWithIndex:0]];
        
        
    }
    return _dataArr;
}




#pragma init -----

- (UIView *)headerView{
    
    if (!_headerView) {
        
        _headerView = [UIView addViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, UNIT_HEIGHT(200)) WithBackgroundColor:getColor(whiteColor)];
        
        
        UIImageView * picImageView = [UIImageView addImgWithImage:@"004"];
        
       self.numLabel = [UILabel addLabelWithFrame:CGRectMake(0, 0, 0, 0) AndText:@"6" AndFont:50 AndAlpha:1.0 AndColor:getColor(whiteColor)];
        
        UILabel * markLabel = [UILabel addLabelWithFrame:CGRectMake(0, 0, 0, 0) AndText:@"°C" AndFont:20 AndAlpha:1.0 AndColor:getColor(whiteColor)];
        
        self.stausLabel = [UILabel addLabelWithFrame:CGRectMake(0, 0, 0, 0) AndText:@"晴" AndFont:20 AndAlpha:1.0 AndColor:getColor(whiteColor)];
        
       self.timeLabel = [UILabel addLabelWithFrame:CGRectMake(0, 0, 0, 0) AndText:@"2018年10月26日/星期五" AndFont:20 AndAlpha:1.0 AndColor:getColor(whiteColor)];
        
        self.palceBtn = [[UIButton alloc] init];
        self.palceBtn.titleLabel.textColor = getColor(whiteColor);
        self.palceBtn.titleLabel.font = DEF_FontSize_18;
        [self.palceBtn addTarget:self action:@selector(placeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self.palceBtn setTitle:self.cityName forState:UIControlStateNormal];
        
     
        
        self.palceBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        self.palceBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        
        [_headerView sd_addSubviews:@[picImageView,self.numLabel,markLabel,self.stausLabel,self.timeLabel, self.palceBtn]];
        
        
       
        
        [self.palceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(UNIT_HEIGHT(20));
            make.left.mas_equalTo(UNIT_WIDTH(10));
            make.height.mas_equalTo(UNIT_HEIGHT(30));
            make.width.mas_equalTo(UNIT_WIDTH(150));
        }];
        
        [picImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
        }];
        
        [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(UNIT_HEIGHT(10));
            make.left.mas_equalTo((SCREEN_WIDTH - 70) / 2);
            make.height.mas_equalTo(UNIT_HEIGHT(70));
        }];
        
        [markLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(UNIT_HEIGHT(10));
            make.left.mas_equalTo(self.numLabel.mas_right).offset(UNIT_WIDTH(10));
            make.height.mas_equalTo(UNIT_HEIGHT(30));
        }];
        
        [self.stausLabel mas_makeConstraints:^(MASConstraintMaker *make) {
             make.bottom.mas_equalTo(self.numLabel.mas_bottom).offset(0);
            make.left.mas_equalTo(self.numLabel.mas_right).offset(UNIT_WIDTH(10));
            make.height.mas_equalTo(UNIT_HEIGHT(30));
        }];
        
        [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.stausLabel.mas_bottom).offset(UNIT_HEIGHT(10));
            make.centerX.mas_equalTo(self.headerView.mas_centerX);
            make.height.mas_equalTo(UNIT_HEIGHT(30));
        }];
        
        
    }
    
    return _headerView;
    
}



//tabelView
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, height64, SCREEN_WIDTH, SCREEN_HEIGHT - height64) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableView.tableHeaderView = self.headerView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = getColor(whiteColor);
    }
    return _tableView;
}
#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        WeatherTableViewDayCell * cell = [WeatherTableViewDayCell cellForTableView:tableView];
        
        if (self.nowWeatherArr.count > 0) {
        
            cell.model = self.nowWeatherArr[indexPath.row];
            
            NSArray * weaArr = @[@"今天",@"明天",@"后天"];
            
            cell.dayLabel.text = weaArr[indexPath.row];
            
        }
        
        return cell;
    }else if (indexPath.section == 2){
        
        WeatherTableViewStatusCell * cell = [WeatherTableViewStatusCell cellForTableView:tableView];
        
        cell.windNumLabel.text = [NSString stringWithFormat:@"%@级",self.dictShow[@"wind_sc"]];
        
        cell.numCodeLabel.text = [NSString stringWithFormat:@"%@%%",self.dictShow[@"hum"]];
        
        cell.tempNumLabel.text = [NSString stringWithFormat:@"%@°C",self.dictShow[@"fl"]];
        
        cell.pressNumLabel.text = [NSString stringWithFormat:@"%@Pa",self.dictShow[@"pres"]];
        
        
        return cell;
        
    }else if (indexPath.section == 3){
        
        WeatherTableViewMoreCell * cell = [WeatherTableViewMoreCell cellForTableView:tableView];
        
       
        
        
        
        return cell;
        
    }else if(indexPath.section == 4){
        
        WeatherTableViewComCell * cell = [WeatherTableViewComCell cellForTableView:tableView];
        
        if (self.lifeArr.count > 0) {
            
            NSDictionary * dic = self.lifeArr[0];
            
            cell.titleLabel.text = dic[@"brf"];
            
            cell.contentLabel.text = dic[@"txt"];
        }
   
        return cell;
        
        
    }else {
        
        WeatherTableViewProgerssCell * cell = [WeatherTableViewProgerssCell cellForTableView:tableView];
     
        if (self.sunArr.count > 0) {
            NSDictionary * dic = self.sunArr[0];
        
            cell.sunLabel1.text = [NSString stringWithFormat:@"日出%@",dic[@"sr"]];
            
            cell.nightLabel2.text = [NSString stringWithFormat:@"日落%@",dic[@"ss"]];
            
            NSDateFormatter *date = [[NSDateFormatter alloc]init];
            
            [date setDateFormat:@"HH:mm"];
            
            NSDate * startD =[date dateFromString:dic[@"sr"]];
            
            NSDate * endD =[date dateFromString:dic[@"ss"]];
            
            NSString * str = self.sunDic[@"loc"];
            
            NSString * str1 = [str substringFromIndex:10];
    
            NSDate * nowD = [date dateFromString:str1];
            
            NSTimeInterval now = [nowD timeIntervalSince1970]*1;
    
            NSTimeInterval  start = [startD timeIntervalSince1970]*1;
       
            NSTimeInterval end = [endD timeIntervalSince1970]*1;
        
            NSTimeInterval value = end - start;
      
             NSTimeInterval value2 = now - start;
            
            float scale = value2 / value;
            
            cell.scale = scale;
  
        }
  
    
        return cell;
        
    }
    
  
}

- (void)drawRect:(CGRect)rect {
    
    
    
  
}
    
    
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        return UNIT_HEIGHT(100);
    }else if (indexPath.section == 2){
        
        return UNIT_HEIGHT(100);
        
    }else if (indexPath.section == 3){
        
        return UNIT_HEIGHT(200);
        
    }else if(indexPath.section == 4){
        
        return UNIT_HEIGHT(100);
    }else{
        
        return UNIT_HEIGHT(250);
    }
 
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}





@end
